package com.example.demo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ffcs.oss.annotation.MyCacheable;
import com.example.demo.client.SmQryClient;
import com.example.demo.client.evt.cssmqry.GetRegionChildrenEvt;
import com.example.demo.client.evt.cssmqry.user.QryUserEvt;
import com.example.demo.client.evt.sysbasequery.MenuConditionEvt;
import com.example.demo.client.evt.sysbasequery.QueryLogEvt;
import com.example.demo.client.evt.sysbasequery.QueryLogInfoEvt;
import com.example.demo.client.evt.sysbasequery.QuerySystemConfigEvt;
import com.example.demo.client.vm.cssmqry.region.RegionVm;
import com.example.demo.client.vm.cssmqry.user.DetailUserVm;
import com.example.demo.client.vm.sysbasequery.*;
import com.example.demo.domain.OperateLog;
import com.example.demo.mapper.LogMapper;
import com.ffcs.oss.param.vm.QueryPageVm;
import com.example.demo.repository.OperateLogRepository;
import com.example.demo.security.SecurityUtils;
import com.example.demo.service.LogService;
import com.example.demo.util.RESTUtil;
import com.example.demo.util.excel.ExcelCreateUtil;
import com.example.demo.web.rest.constant.DatabaseConstant;
import com.example.demo.web.rest.evt.OperateLogEvt;
import com.example.demo.web.rest.evt.PeriodEvt;
import com.example.demo.web.rest.evt.TableIdSizeEvt;
import com.example.demo.web.rest.evt.log.*;
import com.example.demo.web.rest.util.MapUtil;
import com.example.demo.web.rest.vm.LoginLogVm;
import com.example.demo.web.rest.vm.OperateDescVm;
import com.example.demo.web.rest.vm.OperateLogVm;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author zhengmf
 * @Date 2018/12/26  18:14
 */
@Service
@Transactional
public class LogServiceImpl implements LogService {
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private OperateLogRepository operateLogRepository;
    @Autowired
    protected SmQryClient baseQueryClient;
    @Autowired
    private SmQryClient smQryClient;
    @Value("${eslog.url}")
    private String esLogUrl;
    @Value("${eslog.user}")
    private String esUserName;
    @Value("${eslog.password}")
    private String esPassword;
    @Value("${eshttp.urlquery}")
    private String esUrlquery;

    @Override
    public Integer delLoginLogByPeriod(PeriodEvt evt) {
        return logMapper.delLoginLogByPeriod(evt);
    }

    @Override
    public Integer delLoginLogById(Long id) {
        return logMapper.delLoginLogById(id);
    }

    @Override
    public Integer delLogByPeriod(PeriodEvt evt) {
        return logMapper.delLogByPeriod(evt);
    }

    @Override
    public void delLogById(Long id) {
        logMapper.delLogById(id);
    }

    @Override
    public void saveOperateLog(OperateLogEvt evt) {
        OperateLog operateLog = new OperateLog();
        BeanUtils.copyProperties(evt, operateLog);
        operateLog.setHandleUserName(SecurityUtils.getCurrentUserLogin().get());
        operateLog.setOperateTime(new Date());
        TableIdSizeEvt tableIdSizeEvt = new TableIdSizeEvt(DatabaseConstant.TABLE_NAME_OPERATE_LOG, DatabaseConstant.ID_SIZE);
        operateLog.setOperateLogId(baseQueryClient.getTableId(tableIdSizeEvt));
        operateLogRepository.save(operateLog);
    }

    @Override
    public void delOperateLogById(Long id) {
        operateLogRepository.deleteById(id);
    }


    @Override
    public QueryPageVm<Map<String, Object>> queryLogInfo(QueryLogInfoEvt evt) {
//        return logMapper.queryLogInfo(evt);

        if (evt.getPageNo() != null && evt.getPageSize() != null && evt.isCountTotal()) {
            Page page = PageHelper.startPage(evt.getPageNo(), evt.getPageSize(), evt.isCountTotal());
            return QueryPageVm.getInstance(evt, logMapper.queryLogInfo(evt), page.getTotal());
        } else {
            return QueryPageVm.getInstance(evt, logMapper.queryLogInfo(evt), 0l);
        }
    }


    @Override
    public void exportLogAuto(QueryLogEvt evt) {
        List<LogVm> dataList = baseQueryClient.queryLog(evt).getBody().getRecords();
        String[] keyArray = {"id", "moduleDesc", "operateDesc", "operateResult", "endTime",
                "requestIp", "times", "requestUrl", "input", "output"};
        List<String> keys = Arrays.asList(keyArray);
        //将集合中对象的属性对应到List<Map<String,Object>>
        List<Map<String, Object>> list = ExcelCreateUtil.parseListMap(dataList, keys);
        String[] columnArray = {"ID", "模快名称", "功能名称", "操作结果", "结束时间",
                "请求IP", "耗费时间", "请求路径", "输入内容", "输出内容"};
        Workbook workbook = ExcelCreateUtil.createWorkBook(list, keys, Arrays.asList(columnArray), "sheet1");
        try {
            exportLogAutoIO(workbook, "系统日志");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void exportLogAutoIO(Workbook workbook, String fileName) throws IOException {
        QuerySystemConfigEvt evt = new QuerySystemConfigEvt();
        evt.setKey("LOG_BACKUP_PATH");
        String exportPath = (smQryClient.querySystemConfig(evt).getBody().getRecords() != null ? smQryClient.querySystemConfig(evt).getBody().getRecords().get(0).getValue() : "/logBackup");
        Date date = new Date();
        String name = fileName + (date.getMonth() + 1) + "-" + date.getDate() + ".xlsx";
        String dir = exportPath;
        File file = new File(dir, name);
        //创建文件夹
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream out = new FileOutputStream(file);
        workbook.write(out);
        out.close();
    }

    @Override
    public List<Map<String, Object>> countByArea(QryOperateLogEvt evt) {
        DetailUserVm detailUser = smQryClient.qryDetailUser(new QryUserEvt(SecurityUtils.getCurrentUserLogin().get())).getBody();
        List<Map<String, Object>> list = new ArrayList<>();
        GetRegionChildrenEvt getRegionChildrenEvt = new GetRegionChildrenEvt();
        List<Integer> regionTypeList = new ArrayList<>();
        if (StringUtils.isBlank(evt.getParentId()) || StringUtils.isBlank(evt.getType())) {
            getRegionChildrenEvt.setRegionId(detailUser.getRegionVm().getRegionId());
            regionTypeList.add(detailUser.getRegionVm().getRegionType() + 1);
        } else {
            getRegionChildrenEvt.setRegionId(Long.valueOf(evt.getParentId()));
            regionTypeList.add(Integer.valueOf(evt.getType() + 1));
        }
        getRegionChildrenEvt.setRegionTypeList(regionTypeList);
        List<RegionVm> regionVmList = smQryClient.getRegionList(getRegionChildrenEvt);
        if (detailUser != null) {
            RegionVm regionVm = new RegionVm();
            regionVm.setRegionId(detailUser.getRegionVm().getRegionId());
            String regionName = detailUser.getRegionVm().getRegionName();
            regionVm.setRegionName("全国".equals(regionName)?"集团":regionName);
            regionVm.setFullRegionName(detailUser.getRegionVm().getFullRegionName());
            regionVm.setFullRegionId(detailUser.getRegionVm().getFullRegionId());
            regionVm.setRegionType(detailUser.getRegionVm().getRegionType());
            regionVmList.add(regionVm);
        }
        List<Map<String, Object>> operaUserList = logMapper.countOperateUserByArea(evt);
        List<Map<String, Object>> loginUserList = logMapper.countLoginUserByArea(evt);
//        List<Map<String, Object>> validUserList = logMapper.countValidUserByArea();
        for (RegionVm vm :
                regionVmList) {
            Map map = MapUtil.objectToMap(vm);
            map.put("operateCount", 0);
            map.put("loginCount", 0);
            map.put("validUserCount", 0);
            Set<String> setList = new HashSet<>();
            for (Map operaMap :
                    operaUserList) {
                if (vm.getRegionType().equals(detailUser.getRegionVm().getRegionType())) {
                    if (String.valueOf(operaMap.get("fullRegion")).equals(vm.getFullRegionId())) {
                        map.put("operateCount", Integer.parseInt(map.get("operateCount").toString()) + Integer.parseInt(operaMap.get("count").toString()));
                        setList.add(String.valueOf(operaMap.get("loginName")));
                    }
                } else {
                    if (String.valueOf(operaMap.get("fullRegion")).contains(vm.getFullRegionId())) {
                        map.put("operateCount", Integer.parseInt(map.get("operateCount").toString()) + Integer.parseInt(operaMap.get("count").toString()));
                        setList.add(String.valueOf(operaMap.get("loginName")));
                    }
                }
            }
            for (Map loginMap :
                    loginUserList) {
                if (vm.getRegionType().equals(detailUser.getRegionVm().getRegionType())) {
                    if (String.valueOf(loginMap.get("fullRegion")).equals(vm.getFullRegionId())) {
                        map.put("loginCount", Integer.parseInt(map.get("loginCount").toString()) + Integer.parseInt(loginMap.get("count").toString()));
                    }
                } else {
                    if (String.valueOf(loginMap.get("fullRegion")).contains(vm.getFullRegionId())) {
                        map.put("loginCount", Integer.parseInt(map.get("loginCount").toString()) + Integer.parseInt(loginMap.get("count").toString()));
                    }
                }
            }
//            for (Map validMap :
//                    validUserList) {
//                if (String.valueOf(validMap.get("fullRegion")).contains(vm.getFullRegionId())) {
//                    map.put("validUserCount", Integer.parseInt(map.get("validUserCount").toString()) + Integer.parseInt(validMap.get("count").toString()));
//                }
//            }
            map.put("validUserCount",setList.size());
            list.add(map);
        }
        if (evt.getOrderType() == 3) {
            return list.stream().sorted(Comparator.comparing((Map h) -> ((Integer) h.get("validUserCount"))).reversed()).collect(Collectors.toList());
        } else if (evt.getOrderType() == 2) {
            return list.stream().sorted(Comparator.comparing((Map h) -> ((Integer) h.get("loginCount"))).reversed()).collect(Collectors.toList());
        } else {
            return list.stream().sorted(Comparator.comparing((Map<String, Object> h) -> ((Integer) h.get("operateCount"))).reversed()).collect(Collectors.toList());
        }
    }

    @Override
    public List<Map<String, Object>> countByCompany(QryOperateLogEvt evt) {
        DetailUserVm detailUser = smQryClient.qryDetailUser(new QryUserEvt(SecurityUtils.getCurrentUserLogin().get())).getBody();
        evt.setFullRegion(detailUser.getFullRegion());
        List<Map<String, Object>> list = logMapper.countCompany();
//        List<Map<String, Object>> validUserList = logMapper.countValidUserByCompany(evt);
        List<Map<String, Object>> operaUserList = logMapper.countOperateUserByCompany(evt);
        List<Map<String, Object>> loginUserList = logMapper.countLoginUserByCompany(evt);
        for (Map map :
                list) {
            map.put("operateCount", 0);
            map.put("loginCount", 0);
           Set<String> setList = new HashSet<>();
            for (Map operaMap :
                    operaUserList) {
                if (String.valueOf(operaMap.get("company")).equals(String.valueOf(map.get("codeValue")))) {
                    map.put("operateCount", Integer.parseInt(map.get("operateCount").toString()) + Integer.parseInt(operaMap.get("count").toString()));
                    setList.add(String.valueOf(operaMap.get("loginName")));
                }
            }
            for (Map loginMap :
                    loginUserList) {
                if (String.valueOf(loginMap.get("company")).equals(String.valueOf(map.get("codeValue")))) {
                    map.put("loginCount", Integer.parseInt(map.get("loginCount").toString()) + Integer.parseInt(loginMap.get("count").toString()));
                }
            }
//            for (Map validMap :
//                    validUserList) {
//                if (String.valueOf(validMap.get("company")).equals(String.valueOf(map.get("codeValue")))) {
//                    map.put("validUserCount", Integer.parseInt(map.get("validUserCount").toString()) + Integer.parseInt(validMap.get("count").toString()));
//                }
//            }
            map.put("validUserCount", setList.size());
        }
        if (evt.getOrderType() == 3) {
            return list.stream().sorted(Comparator.comparing((Map h) -> (Integer.parseInt(h.get("validUserCount").toString()))).reversed()).collect(Collectors.toList());
        } else if (evt.getOrderType() == 2) {
            return list.stream().sorted(Comparator.comparing((Map h) -> (Integer.parseInt(h.get("loginCount").toString()))).reversed()).collect(Collectors.toList());
        } else {
            return list.stream().sorted(Comparator.comparing((Map<String, Object> h) -> (Integer.parseInt(h.get("operateCount").toString()))).reversed()).collect(Collectors.toList());
        }
    }

    @Override
    public List<Map<String, Object>> countByUser(QryOperateLogEvt evt) {
        DetailUserVm detailUser = smQryClient.qryDetailUser(new QryUserEvt(SecurityUtils.getCurrentUserLogin().get())).getBody();
        evt.setFullRegion(detailUser.getFullRegion());

        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> operaUserList = logMapper.countOperateUserByUser(evt);
        List<Map<String, Object>> loginUserList = logMapper.countLoginUserByUser(evt);
        for (Map operaUser :
                operaUserList) {
            operaUser.put("loginCount", 0);
            operaUser.put("regionName",getRegionNameByFullRegionName(String.valueOf(operaUser.get("fullRegionName"))));
            list.add(operaUser);
        }
        for (Map loginUser :
                loginUserList) {
            Boolean isExists = false;
            for (Map map : list) {
                if (String.valueOf(map.get("loginName")).equals(String.valueOf(loginUser.get("loginName")))) {
                    map.put("loginCount", Integer.parseInt(String.valueOf(map.get("loginCount"))) + Integer.parseInt(String.valueOf(loginUser.get("loginCount"))));
                    isExists = true;
                }
            }
            if (!isExists) {
                loginUser.put("operateCount", 0);
                loginUser.put("regionName",getRegionNameByFullRegionName(String.valueOf(loginUser.get("fullRegionName"))));
                list.add(loginUser);
            }
        }

        if (evt.getOrderType() == 2) {
            return list.stream().sorted(Comparator.comparing((Map<String, Object> h) -> (Integer.parseInt(h.get("loginCount").toString()))).reversed()).collect(Collectors.toList());
        } else {
            return list.stream().sorted(Comparator.comparing((Map<String, Object> h) -> (Integer.parseInt(h.get("operateCount").toString()))).reversed()).collect(Collectors.toList());
        }
    }

    @Override
    public List<Map<String, Object>> countByFun(QryOperateLogEvt evt) {
        DetailUserVm detailUser = smQryClient.qryDetailUser(new QryUserEvt(SecurityUtils.getCurrentUserLogin().get())).getBody();
        evt.setFullRegion(detailUser.getFullRegion());

        List<MenuTreeVm> menuTreeVmList = smQryClient.getMenuTreeByCondition(new MenuConditionEvt()).getBody();
        List<Map<String, Object>> operateList = logMapper.countByFun(evt);
        List<Map<String, Object>> list = getMenuTreeList(menuTreeVmList, operateList);
        return list.stream().sorted(Comparator.comparing((Map<String, Object> h) -> (Integer.parseInt(h.get("operateCount").toString()))).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<Map<String, Object>> countByBusy(QryOperateLogEvt evt) {
        DetailUserVm detailUser = smQryClient.qryDetailUser(new QryUserEvt(SecurityUtils.getCurrentUserLogin().get())).getBody();
        evt.setFullRegion(detailUser.getFullRegion());

        List<Map<String, Object>> operateList = logMapper.countOperateUserByBusy(evt);
        List<Map<String, Object>> loginList = logMapper.countLoginUserByBusy(evt);
        for (Map operateMap :
                operateList) {
            operateMap.put("loginCount", 0l);
            operateMap.put("fullTime", (String.valueOf(operateMap.get("time")) + ":00:00"));
            for (Map loginMap :
                    loginList) {
                if (String.valueOf(operateMap.get("time")).equals(String.valueOf(loginMap.get("time")))){
                    operateMap.put("loginCount", loginMap.get("loginCount"));
                }
            }

        }
        return operateList.stream().sorted(Comparator.comparing((Map<String, Object> h) -> (Integer.parseInt(h.get("operateCount").toString()))).reversed()).collect(Collectors.toList());
    }

    @Override
    public QueryPageVm<OperateLogVm> listOperateLog(QueryOperateLogEvt evt) {
        if (StringUtils.isBlank(evt.getFullRegion())) {
            DetailUserVm detailUser = smQryClient.qryDetailUser(new QryUserEvt(SecurityUtils.getCurrentUserLogin().get())).getBody();
            evt.setFullRegion(detailUser.getFullRegion());
        }
        if (evt.getPageNo() != null && evt.getPageSize() != null && evt.isCountTotal()) {
            Page page = PageHelper.startPage(evt.getPageNo(), evt.getPageSize(), evt.isCountTotal());
            List<OperateLogVm> list = logMapper.listOperateLog(evt);
            changeOperaLogCodeToDesc(list);
            return QueryPageVm.getInstance(evt, list, page.getTotal());
        } else {
            List<OperateLogVm> list = logMapper.listOperateLog(evt);
            changeOperaLogCodeToDesc(list);
            return QueryPageVm.getInstance(evt, list, 0l);
        }
    }

    @Override
    public QueryPageVm<LoginLogVm> listLoginLog(LoginLogEvt evt) {
        if (evt.getPageNo() != null && evt.getPageSize() != null && evt.isCountTotal()) {
            Page page = PageHelper.startPage(evt.getPageNo(), evt.getPageSize(), evt.isCountTotal());
            List<LoginLogVm> list = logMapper.listLoginLog(evt);
            return QueryPageVm.getInstance(evt, list, page.getTotal());
        } else {
            List<LoginLogVm> list = logMapper.listLoginLog(evt);
            return QueryPageVm.getInstance(evt, list, 0l);
        }
    }

    @Override
    public QueryPageVm<Map<String, Object>> queryLogInfoEs(QueryLogInfoEvt evt) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        QueryPageVm<Map<String, Object>> instance = QueryPageVm.getInstance(evt, list, 0l);
        instance.setPageNo(evt.getPageNo());
        instance.setPageSize(evt.getPageSize());
        String url = esLogUrl;
        if (StringUtil.isNotEmpty(evt.getSelectValue())) {
            //如果为日期类型 必须是sm_log索引
            url = url.replace("sm_log", "sm_log" + evt.getSelectValue());
        }
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtil.isNotEmpty(evt.getRequestIp())) {
            boolQuery.must(QueryBuilders.wildcardQuery("requestIp",  "*" + evt.getRequestIp() + "*"));
        }
        if (StringUtil.isNotEmpty(evt.getModuleDesc())) {
            boolQuery.must(QueryBuilders.wildcardQuery("moduleDesc", "*" + evt.getModuleDesc() + "*"));
        }
        if (StringUtil.isNotEmpty(evt.getCreateUserName())) {
            boolQuery.must(QueryBuilders.wildcardQuery("createUserName", "*" + evt.getCreateUserName() + "*"));
        }
        if (StringUtil.isNotEmpty(evt.getRetrieval())) {
            boolQuery.should(QueryBuilders.wildcardQuery("requestIp",  "*" + evt.getRetrieval() + "*"))
                    .should(QueryBuilders.wildcardQuery("moduleDesc",  "*" + evt.getRetrieval() + "*"))
                    .should(QueryBuilders.wildcardQuery("createUserName",  "*" + evt.getRetrieval() + "*"));
        }

        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        queryBuilder = boolQuery;
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.sort("DATE.keyword", SortOrder.DESC);
        searchSourceBuilder.size(evt.getPageSize());
        searchSourceBuilder.from((evt.getPageNo() -1 ) * evt.getPageSize());
        RESTUtil restUtil = new RESTUtil(url, searchSourceBuilder.toString(), null, esUserName, esPassword);
        String respBody = restUtil.loadPost();
        if (org.apache.commons.lang.StringUtils.isNotBlank(respBody)) {
            JSONObject jsonObject = JSONObject.parseObject(respBody);
            JSONObject summaryJsonObj = jsonObject.getJSONObject("hits");
            instance.setTotal(summaryJsonObj.getLong("total"));
            JSONArray jsonArray = summaryJsonObj.getJSONArray("hits");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject resource = jsonArray.getJSONObject(i).getJSONObject("_source");
                list.add(resource.getInnerMap());
            }
        }
        instance.setRecords(list);
        return instance;
    }

    @Override
    public List<LogSelectVm> queryLogSelect() throws Exception {
        List<LogSelectVm> logSelectVms = new ArrayList<>();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        queryBuilder = boolQuery;
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.sort("selectType", SortOrder.DESC);
        searchSourceBuilder.size(10000);
        searchSourceBuilder.from(0);
        RESTUtil restUtil = new RESTUtil(esUrlquery, searchSourceBuilder.toString(), null, esUserName, esPassword);
        String respBody = restUtil.loadPost();
        if (org.apache.commons.lang.StringUtils.isNotBlank(respBody)) {
            JSONObject jsonObject = JSONObject.parseObject(respBody);
            JSONObject summaryJsonObj = jsonObject.getJSONObject("hits");
            JSONArray jsonArray = summaryJsonObj.getJSONArray("hits");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject resource = jsonArray.getJSONObject(i).getJSONObject("_source");
                LogSelectVm logSelectVm = new LogSelectVm();
                logSelectVm.setSelectType(resource.getString("selectType"));
                logSelectVm.setSelectValue(resource.getString("selectValue"));
                logSelectVms.add(logSelectVm);
            }
        }
        return logSelectVms;
    }

    @Override
    public void saveMenuLog(MenuLogEvt evt, HttpServletRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        evt.setCreateUserName(SecurityUtils.getCurrentUserLogin().get());
        evt.setCreateTime(dateFormat.format(new Date()));
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        evt.setIp(ip);
        logMapper.saveMenuLog(evt);
    }

    @Override
    public  QueryPageVm queryMenuLog(QueryMenuLogEvt evt) {
        if (evt.isCountTotal()) {
            Page page = PageHelper.startPage(evt.getPageNo(), evt.getPageSize(), evt.isCountTotal());
            return QueryPageVm.getInstance(evt, logMapper.queryMenuLog(), page.getTotal());
        } else {
            Page page = PageHelper.startPage(evt.getPageNo(), evt.getPageSize(), evt.isCountTotal());
            return QueryPageVm.getInstance(evt, logMapper.queryMenuLog(), 0l);
        }
    }

    private List<Map<String, Object>> getMenuTreeList(List<MenuTreeVm> menuTreeVmList, List<Map<String, Object>> operateList) {
        List<Map<String, Object>> list = new ArrayList<>();
        Integer count = 0;
        for (MenuTreeVm vm :
                menuTreeVmList) {
            count = 0;
            Map map = MapUtil.objectToMap(vm);
            if (vm.getChildren() != null && vm.getChildren().size() > 0) {
                List<Map<String, Object>> childList = getMenuTreeList(vm.getChildren(), operateList);
                map.put("children", childList);
                for (Map childMap :
                        childList) {
                    count += Integer.parseInt(String.valueOf(childMap.get("operateCount")));
                }
            }

            map.put("operateCount", count);
            for (Map operateMap :
                    operateList) {
                if (vm.getMenuType().equals(String.valueOf(operateMap.get("moduleType")))
                        && (vm.getNameEn().equals(String.valueOf(operateMap.get("operateAction"))))
                        || vm.getPermissionCode().equals(String.valueOf(map.get("operateAction")))) {
                    map.put("operateCount", Integer.parseInt(String.valueOf(operateMap.get("count"))) + Integer.parseInt(String.valueOf(map.get("operateCount"))));

                }
            }
            list.add(map);
        }
        return list;
    }

    private String getRegionNameByFullRegionName(String regionName) {
        if (StringUtils.isBlank(regionName)) {
            return null;
        }
        String[] strs = regionName.split("/");
        if (strs.length == 1 && strs[0].equals("全国")) {
            return "集团";
        }else {
            return strs[strs.length - 1];
        }
    }

    private void changeOperaLogCodeToDesc(List<OperateLogVm> list) {
        UserStaticDataVm userStaticDataVm = smQryClient.getUserStaticData().getBody();

        for (OperateLogVm vm :
                list) {
            vm.setRegionName(getRegionNameByFullRegionName(vm.getFullRegionName()));
            for (int i = 0; i < userStaticDataVm.getCompany().size(); i++) {
                CodeVm codeVm = userStaticDataVm.getCompany().get(i);
                if (StringUtils.isNotBlank(vm.getCompany()) && codeVm.getValue().equals(vm.getCompany())) {
                    vm.setCompanyDesc(codeVm.getDescName());
                }
            }
            for (int i = 0; i < userStaticDataVm.getUserType().size(); i++) {
                CodeVm codeVm = userStaticDataVm.getUserType().get(i);
                if (vm.getUserType() > 0 && codeVm.getValue().equals(String.valueOf(vm.getUserType()))) {
                    vm.setUserTypeDesc(codeVm.getDescName());
                }
            }
            vm.setOperateActionDesc(getOperateDesc(vm.getOperateAction()));
        }
    }

    private String getOperateDesc(String operate) {
        if (StringUtils.isBlank(operate)) {
            return "查询";
        }
        for(OperateDescVm vm : getOperateDescList()) {
            if (operate.toUpperCase().contains(vm.getValue())) {
                return vm.getName();
            }
        }
        return "查询";
    }

    @MyCacheable
    private List<OperateDescVm> getOperateDescList() {
        return logMapper.getOperateDescList();
    }
}
